﻿using DocumentFormat.OpenXml.Office2010.Excel;
using Magicodes.ExporterAndImporter.Core;
using Magicodes.ExporterAndImporter.Excel;
using Mapster;
using Microsoft.Extensions.Configuration;
using NP.BPMReportPlatform.Cadre;
using NP.BPMReportPlatform.Contract.Dtos;
using NP.BPMReportPlatform.CustomerProfileConfig;
using NP.BPMReportPlatform.CustomerProfileConfig.Dto;
using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.Entities.BPM_Business;
using NP.BPMReportPlatform.Entities.BPM_Platform;
using NP.BPMReportPlatform.Hana;
using OfficeOpenXml.FormulaParsing.Utilities;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;

namespace NP.BPMReportPlatform.CustomerProfileConfig
{
    /// <summary>
    /// 客户档案配置接口服务
    /// </summary>
    public class CustomerProfileConfigAppService : BPMReportPlatformAppService, ICustomerProfileConfigAppService
    {
        private readonly SqlSugarClient _dbBusiness;
        private readonly SqlSugarClient _dbProcess;
        private readonly SqlSugarClient _dbPlatform;
        private readonly IExcelImporter _importer;
        private readonly IHanaService _hanaService;

        public CustomerProfileConfigAppService(ISqlSugarAppService sqlSugarAppService, IConfiguration configuration, IExcelImporter importer, 
            IHanaService hanaService)
        {
            _dbBusiness = sqlSugarAppService.GetBusinessInstance();
            _dbProcess = sqlSugarAppService.GetProcessInstance();
            _dbPlatform = sqlSugarAppService.GetPlatformInstance();
            _importer = importer;
            _hanaService = hanaService;
        }
        /// <summary>
        /// 根据送达方编码找售达方编码
        /// </summary>
        /// <param name="business"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public async Task<List<SDFInfoOutput>> GetSDFInfo(string business, string code)
        {
            var result = (await _hanaService.GetSDFInfo(business,code)).ToList();
           return result;
        }
        /// <summary>
        /// 查询数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<GetCustomerProfileConfigOutput>> GetAllAsync(GetCustomerProfileConfigInput input)
        {
            RefAsync<int> totalCount = 0;
            var listViewDto = await _dbBusiness.Queryable<CustomerProfileConfigHeader>()
                .WhereIF(!input.IsQueryAll, x => x.AddUserCode.Equals(CurrentUser.UserName)||x.JSDDCode.Equals(CurrentUser.UserName))
                .WhereIF(!string.IsNullOrWhiteSpace(input.Business), a => a.Business.Equals(input.Business))
                .WhereIF(!string.IsNullOrWhiteSpace(input.Industry), a => a.Industry.Contains(input.Industry))
                .WhereIF(!string.IsNullOrWhiteSpace(input.Area), a => a.Area.Contains(input.Area))
                .WhereIF(!string.IsNullOrWhiteSpace(input.CustomerCode), a => a.CustomerCode.Contains(input.CustomerCode)|| a.CustomerName.Contains(input.CustomerCode))
                .WhereIF(!string.IsNullOrWhiteSpace(input.ProductionLine), a => a.ProductionLine.Contains(input.ProductionLine))
                .WhereIF(!string.IsNullOrWhiteSpace(input.ProductName), a => a.ProductName.Contains(input.ProductName))
                .WhereIF(!string.IsNullOrWhiteSpace(input.JSDD), a => a.CustomerAttribution.Contains(input.JSDD))
                .WhereIF(!string.IsNullOrWhiteSpace(input.XSDD), a => a.XSDDCode.Contains(input.XSDD) || a.XSDDName.Contains(input.XSDD))
                .WhereIF(!string.IsNullOrWhiteSpace(input.CustomerAttribution), a => a.CustomerAttribution.Contains(input.CustomerAttribution))
                .WhereIF(!input.State.IsNullOrEmpty(), a => SqlFunc.ContainsArray<string>(input.State.ToArray(), a.State))
                .Select(a => new GetCustomerProfileConfigOutput()
                {
                    Id = a.Id,
                    Business = a.Business,
                    Industry = a.Industry,
                    Area = a.Area,
                    CustomerType = a.CustomerType,
                    CustomerCode = a.CustomerCode,
                    SDFCode2 = a.SDFCode2,
                    SDFName2 = a.SDFName2,
                    CustomerName = a.CustomerName,
                    ProductionLine = a.ProductionLine,
                    ProductName = a.ProductName,
                    CustomerAttribution = a.CustomerAttribution,
                    State = a.State,
                    JYDate = a.JYDate,
                    TCORHC = a.TCORHC,
                    Province = a.Province,
                    City = a.City,
                    TestingFrequency = a.TestingFrequency,
                    JSDDCode = a.JSDDCode,
                    JSDDName = a.JSDDName,
                    XSDDCode = a.XSDDCode,
                    XSDDName = a.XSDDName,
                    AddTime = a.AddTime,
                    UpdateTime = a.UpdateTime,
                    AddUserName = a.AddUserName,
                    UpdateUserName = a.UpdateUserName                   
                }).OrderBy(a=>a.AddTime,OrderByType.Desc)
                .ToPageListAsync(input.PageIndex, input.PageSize, totalCount);
                foreach (var item in listViewDto)
                {
                var details = await _dbBusiness.Queryable<CustomerProfileConfigDetail>().Where(x => x.ParentId == item.Id).OrderBy(x => x.SortNo).ToListAsync();
                item.InnerDetails = details;
                }
             
            //返回结果
            return new PagedResultDto<GetCustomerProfileConfigOutput>()
            {
                TotalCount = totalCount,
                Items = listViewDto
            };
        }
        /// <summary>
        /// 查询检测指标
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<List<CustomerProfileConfigDetail>> GetIndicatorsList(Guid  id)
        {
            var list = await _dbBusiness.Queryable<CustomerProfileConfigDetail>()
                .Where(x => x.ParentId == id && x.IsEnable =="是").OrderBy(x=>x.SortNo).ToListAsync();
            return list;  
        }

        /// <summary>
        /// 查询修改记录
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<List<EditRecordListOutput>> GetEditRecordList(Guid id)
        {
            var list = await _dbBusiness.Queryable<CustomerProfileEditRecord>().Where(x => x.ParentId == id)
                .Select(x=>new EditRecordListOutput()
                {
                    ParentId= x.ParentId,
                    Version =x.Version,
                    CreateTime =x.CreateTime,
                    Editor = x.Editor,
                    OptionType = x.OptionType
                }).Distinct().OrderBy(x=>x.Version, OrderByType.Desc).ToListAsync();
            return list;
        }

        /// <summary>
        /// 查询修改记录详情
        /// </summary>
        /// <param name="id"></param>
        /// <param name="version"></param>
        /// <returns></returns>
        public async Task<List<EditRecordDetailOutput>> GetEditRecordDetail(Guid id,int version)
        {
            var list = await _dbBusiness.Queryable<CustomerProfileEditRecord>().Where(x => x.ParentId == id&& x.Version==version)
                .Select(x => new EditRecordDetailOutput()
                {
                    ParentId = x.ParentId,
                    Version = x.Version,
                    SortNo =x.SortNo,
                    FieldCode = x.FieldCode,
                    FieldName = x.FieldName,
                    OldValue = x.OldValue,
                    NewValue = x.NewValue
                }).Distinct().OrderBy(x=>x.SortNo).ToListAsync();
            return list;
        }

        public async Task<List<GetCustomerProfileConfigOutput>> ExportAsync(GetCustomerProfileConfigInput input)
        {
            var listViewDto = await _dbBusiness.Queryable<CustomerProfileConfigHeader>()
                .WhereIF(!input.IsQueryAll, x => x.AddUserCode.Equals(CurrentUser.UserName) || x.JSDDCode.Equals(CurrentUser.UserName))
                .WhereIF(!string.IsNullOrWhiteSpace(input.Business), a => a.Business.Equals(input.Business))
                .WhereIF(!string.IsNullOrWhiteSpace(input.Industry), a => a.Industry.Contains(input.Industry))
                .WhereIF(!string.IsNullOrWhiteSpace(input.Area), a => a.Area.Contains(input.Area))
                .WhereIF(!string.IsNullOrWhiteSpace(input.CustomerCode), a => a.CustomerCode.Contains(input.CustomerCode) || a.CustomerName.Contains(input.CustomerCode))
                .WhereIF(!string.IsNullOrWhiteSpace(input.ProductionLine), a => a.ProductionLine.Contains(input.ProductionLine))
                .WhereIF(!string.IsNullOrWhiteSpace(input.ProductName), a => a.ProductName.Contains(input.ProductName))
                .WhereIF(!string.IsNullOrWhiteSpace(input.JSDD), a => a.CustomerAttribution.Contains(input.JSDD))
                .WhereIF(!string.IsNullOrWhiteSpace(input.XSDD), a => a.XSDDCode.Contains(input.XSDD) || a.XSDDName.Contains(input.XSDD))
                .WhereIF(!string.IsNullOrWhiteSpace(input.CustomerAttribution), a => a.CustomerAttribution.Contains(input.CustomerAttribution))
                .WhereIF(!input.State.IsNullOrEmpty(), a => SqlFunc.ContainsArray<string>(input.State.ToArray(), a.State))
                .Select(a => new GetCustomerProfileConfigOutput()
                {
                    Id = a.Id,
                    Business = a.Business,
                    Industry = a.Industry,
                    Area = a.Area,
                    CustomerType = a.CustomerType,
                    CustomerCode = a.CustomerCode,
                    CustomerName = a.CustomerName,
                    SDFCode2 = a.SDFCode2,
                    SDFName2 = a.SDFName2,
                    ProductionLine = a.ProductionLine,
                    ProductName = a.ProductName,
                    CustomerAttribution = a.CustomerAttribution,
                    State = a.State,
                    JYDate = a.JYDate,
                    TCORHC = a.TCORHC,
                    Province = a.Province,
                    City = a.City,
                    TestingFrequency = a.TestingFrequency,
                    JSDDCode = a.JSDDCode,
                    JSDDName = a.JSDDName,
                    XSDDCode = a.XSDDCode,
                    XSDDName = a.XSDDName,
                    AddTime =a.AddTime,
                    UpdateTime= a.UpdateTime,
                    AddUserName = a.AddUserName,
                    UpdateUserName =a.UpdateUserName
                }).OrderBy(a => a.AddTime, OrderByType.Desc).ToListAsync();
            return listViewDto;
        }

        /// <summary>
        /// 保存客户档案 配置
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task SaveAsync(SaveCustomerProfileConfigInput input)
        {
            try
            {
                var userName = _dbPlatform.Queryable<Users>().Where(x => x.WorkNumber.Equals(CurrentUser.UserName)).First().UserName;
                _dbBusiness.BeginTran();
                var mapperInput = input.Adapt<CustomerProfileConfigHeader>();
                if (input.Id != Guid.Empty)
                {
                    var currentData = await _dbBusiness.Queryable<CustomerProfileConfigHeader>()
                            .Where(x => x.Business == mapperInput.Business && x.ProductionLine == mapperInput.ProductionLine && x.Id!=input.Id)
                            .WhereIF(!string.IsNullOrWhiteSpace(mapperInput.CustomerCode), x => x.CustomerCode.Equals(mapperInput.CustomerCode))
                            .WhereIF(!string.IsNullOrWhiteSpace(mapperInput.CustomerName), x => x.CustomerName.Equals(mapperInput.CustomerName))
                            .FirstAsync();
                    if (currentData != null)
                    {
                        throw new Exception($"事业部:{mapperInput.Business} 送达方代码：{mapperInput.CustomerCode} 送达方名称：{mapperInput.CustomerName} 产线名称：{mapperInput.ProductionLine}，已存在！请勿重复添加！");

                    }
                    await UpdateVersion("修改", input, input.Id);
                    mapperInput.UpdateTime = DateTime.Now;
                    mapperInput.UpdateUserName = userName;
                    await _dbBusiness.Updateable(mapperInput).ExecuteCommandAsync();
                    //指标配置
                    var innerDetails = mapperInput.InnerDetails;
                    foreach (var item in innerDetails)
                    {
                        item.ParentId = mapperInput.Id;
                    }

                    await _dbBusiness.Updateable(innerDetails).ExecuteCommandAsync();
                   
                }
                else
                {
                    var currentData = await _dbBusiness.Queryable<CustomerProfileConfigHeader>()
                            .Where(x => x.Business == mapperInput.Business && x.ProductionLine == mapperInput.ProductionLine)
                            .WhereIF(!string.IsNullOrWhiteSpace(mapperInput.CustomerCode), x => x.CustomerCode.Equals(mapperInput.CustomerCode))
                            .WhereIF(!string.IsNullOrWhiteSpace(mapperInput.CustomerName), x => x.CustomerName.Equals(mapperInput.CustomerName))
                            .FirstAsync();
                    if (currentData != null)
                    {
                        throw new Exception($"事业部:{mapperInput.Business} 送达方代码：{mapperInput.CustomerCode} 送达方名称：{mapperInput.CustomerName} 产线名称：{mapperInput.ProductionLine}，已存在！请勿重复添加！");
                        
                    }
                    mapperInput.Id = Guid.NewGuid();
                    mapperInput.AddUserName = userName;
                    mapperInput.AddTime = DateTime.Now;
                    await _dbBusiness.Insertable(mapperInput).ExecuteCommandAsync();
                    //指标配置
                    var innerDetails = mapperInput.InnerDetails;
                    foreach (var item in innerDetails)
                    {
                        item.Id = Guid.NewGuid();
                        item.ParentId = mapperInput.Id;
                        item.IsEnable = item.IsEnable != "是" ? "否" : "是";
                    }
                    await _dbBusiness.Insertable(innerDetails).ExecuteCommandAsync();
                }
                _dbBusiness.CommitTran();
            }
            catch (Exception e)
            {
                _dbBusiness.RollbackTran();
                throw e;
            }
           
        }

        /// <summary>
        /// 删除客户档案 配置
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task DeleteAsync(Guid id)
        {
            try
            { 
                await UpdateVersion("删除", new SaveCustomerProfileConfigInput() ,id);
                await _dbBusiness.Deleteable<CustomerProfileConfigHeader>().Where(x => x.Id.Equals(id)).ExecuteCommandAsync();
                await _dbBusiness.Deleteable<CustomerProfileConfigDetail>().Where(x => x.ParentId.Equals(id)).ExecuteCommandAsync();
            }
            catch (Exception e)
            {
                throw e;
            }
              
        }

        /// <summary>
        /// 批量导入Excel
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public async Task<ImportResultExt<ImportCustomerProfileConfigTemplate>> ImporterExcel(byte[] bytes)
        {
            try
            {
                Stream stream = new MemoryStream(bytes);
                Stream stream2 = new MemoryStream(bytes);
                List<CustomerProfileConfigHeader> list = new List<CustomerProfileConfigHeader>();
                List<CustomerProfileConfigDetail>  details = new List<CustomerProfileConfigDetail>();
                var rstHeader = await _importer.Import<ImportCustomerProfileConfigTemplate>(stream);
                var rstDetail = await _importer.Import<ImportCustomerProfileConfigDetailTemplate>(stream2);
                var importHeaderData = rstHeader?.Data;
                var importDetailData = rstDetail?.Data;
                var userName = _dbPlatform.Queryable<Users>().Where(x => x.WorkNumber.Equals(CurrentUser.UserName)).First().UserName;
                if (!rstHeader.HasError)
                {
                    //验证事业部+送达方代码+产线名称），如相同，则提示客户信息已添加，勿重复添加
                    var importDataGruop1 = importHeaderData.Where(x=>!x.CustomerCode.IsNullOrEmpty()).GroupBy(x => new { x.Business, x.CustomerCode, x.ProductionLine }).ToList();
                    foreach (var item1 in importDataGruop1)
                    {
                        var currentItem = item1.ToList();
                        if (currentItem.Count > 1)
                        {
                            rstHeader.Exception = new Exception($"导入模板中,事业部:{currentItem[0].Business}送达方代码:{currentItem[0].CustomerCode}产线名称:{currentItem[0].ProductionLine}有重复！");
                        }
                    }
                    //验证事业部+送达方名称+产线名称），如相同，则提示客户信息已添加，勿重复添加
                    var importDataGruop2 = importHeaderData.Where(x => x.CustomerCode.IsNullOrEmpty() && !x.CustomerName.IsNullOrEmpty()).GroupBy(x => new { x.Business, x.CustomerName, x.ProductionLine }).ToList();
                    foreach (var item1 in importDataGruop1)
                    {
                        var currentItem = item1.ToList();
                        if (currentItem.Count > 1)
                        {
                            rstHeader.Exception = new Exception($"导入模板中,事业部:{currentItem[0].Business}送达方名称:{currentItem[0].CustomerCode}产线名称:{currentItem[0].ProductionLine}有重复！");
                        }
                    }
                    if (importDetailData.Count==0)
                    {
                        rstHeader.Exception = new Exception($"导入模板中,检测指标配置没有数据！");
                    }
                    // 获取基础连带数据
                    int Index = 1;
                    foreach (var item in importHeaderData)
                    {
                        Index++;
                        if (!(item.Business=="A8"|| item.Business == "A9"|| item.Business == "IC"))
                        {
                            rstHeader.Exception = new Exception($"第{Index}行，事业部:{item.Business} 不规范！");
                            break;
                        }
                        // 查询客户信息
                        if (item.CustomerCode.IsNullOrEmpty() && item.CustomerName.IsNullOrEmpty())
                        {
                            rstHeader.Exception = new Exception($"第{Index}行，送达方代码和送达方名称至少填一个！");
                            break;
                        }else if (!item.CustomerCode.IsNullOrEmpty())
                        {
                            // 查询客户信息
                            var customerList = await _hanaService.GetKNA1CustomerAsync(item.CustomerCode);
                            if (customerList.Count == 0)
                            {
                                rstHeader.Exception = new Exception($"第{Index}行，送达方代码:{item.CustomerCode} 未查到数据！");
                                break;
                            }
                            else
                            {
                                item.CustomerCode = customerList[0].Code;
                                item.CustomerName = customerList[0].Name;
                                //查询对应的售达方信息
                                var sdfList = await GetSDFInfo(item.Business,item.CustomerCode);
                                if (sdfList.Count > 0)
                                {
                                    item.SDFCode2 = sdfList[0].SDFCode2;
                                    item.SDFName2 = sdfList[0].SDFName2;
                                }
                            }

                        }
                       
                        var currentData = await _dbBusiness.Queryable<CustomerProfileConfigHeader>()
                            .Where(x => x.Business == item.Business && x.ProductionLine == item.ProductionLine)
                            .WhereIF(!string.IsNullOrWhiteSpace(item.CustomerCode), x => x.CustomerCode.Equals(item.CustomerCode))
                            .WhereIF(!string.IsNullOrWhiteSpace(item.CustomerName), x => x.CustomerName.Equals(item.CustomerName))
                            .FirstAsync();
                        if (currentData != null)
                        {
                            rstHeader.Exception = new Exception($"第{Index}行，事业部:{item.Business} 送达方代码：{item.CustomerCode} 送达方名称：{item.CustomerName} 产线名称：{item.ProductionLine}，已存在！请勿重复添加！");
                            break;
                        }
                        //查询技术担当
                        var jsddUser = await GetUserDetail(item.JSDDCode.Trim());
                        if (jsddUser == null)
                        {
                            rstHeader.Exception = new Exception($"第{Index}行，技术担当:{item.JSDDCode} 未查到数据！");
                            break;
                        }
                        //查询销售担当
                        var xsddUser = await GetUserDetail(item.XSDDCode.Trim());
                        if (xsddUser==null)
                        {
                            rstHeader.Exception = new Exception($"第{Index}行，销售担当:{item.XSDDCode} 未查到数据！");
                            break;
                        }
                        var currentDetail = importDetailData.ToList();
                        if (currentDetail.Count != 81)
                        {
                            rstHeader.Exception = new Exception($"检测指标配置数据不符合模板要求，检测指标配置必须81行！");
                            break;
                        }
                        CustomerProfileConfigHeader customerProfile = new CustomerProfileConfigHeader()
                        {
                            Id = Guid.NewGuid(),
                            AddTime = DateTime.Now,
                            AddUserName = userName,
                            Business = item.Business,
                            Industry = item.Industry,
                            Area = item.Area,
                            CustomerType = item.CustomerType,
                            CustomerCode = item.CustomerCode,
                            CustomerName = item.CustomerName,
                            SDFCode2 = item.SDFCode2,
                            SDFName2 = item.SDFName2,
                            ProductionLine = item.ProductionLine,
                            CustomerAttribution = item.CustomerAttribution==null?"": item.CustomerAttribution,
                            State = item.State,
                            JYDate = item.JYDate,
                            TCORHC = item.TCORHC,
                            Province = item.Province,
                            City = item.City,
                            TestingFrequency = item.TestingFrequency,
                            JSDDCode = jsddUser.WorkNumber,
                            JSDDName = jsddUser.UserName,
                            XSDDCode = xsddUser.WorkNumber,
                            XSDDName = xsddUser.UserName,
                        };
                        list.Add(customerProfile);
                        if (!rstDetail.HasError)
                        {
                            // 获取基础连带数据
                            int Index2 = 0;
                            foreach (var item2 in currentDetail)
                            {
                                Index2++;
                                var detail = new CustomerProfileConfigDetail()
                                {
                                    Id = Guid.NewGuid(),
                                    SortNo = Index2,
                                    ParentId = customerProfile.Id,
                                    Project1 = item2.Project1,
                                    Project2 = item2.Project2,
                                    Project3 = item2.Project3,
                                    MinValue = item2.MinValue,
                                    MaxValue = item2.MaxValue,
                                    IsEnable = item2.IsEnable!= "是" ? "否" : "是",
                                    StandardValue = item2.StandardValue,
                                };
                                details.Add(detail);
                            }
                        }
                    }
                }
               
                if (!rstHeader.HasError && !rstDetail.HasError && rstHeader.Exception == null && rstDetail.Exception == null)
                {
                    await _dbBusiness.Insertable(list).ExecuteCommandAsync();
                    await _dbBusiness.Insertable(details).ExecuteCommandAsync();
                }
                var resp = new ImportResultExt<ImportCustomerProfileConfigTemplate>()
                {
                    Data = importHeaderData,
                    Exception = rstHeader.Exception,
                    RowErrors = rstHeader.RowErrors,
                    TemplateErrors = rstHeader.TemplateErrors
                };
                return resp;
            }
            catch (Exception e)
            {
                throw e;
            }
         
        }
        /// <summary>
        /// 根据工号或域账号查询员工信息
        /// </summary>
        /// <param name="workNumber"></param>
        /// <returns></returns>
        private async Task<Users> GetUserDetail(string workNumber)
        {
            if (workNumber.StartsWith("E00"))
            {
                workNumber = workNumber.Replace('E', '0');
            }
            if (workNumber.IsNumeric()&& workNumber.Length<8)
            {
                // 工号时，左补0，最多8位
                workNumber = workNumber.ToString().PadLeft(8, '0');
            }
            return await _dbPlatform.Queryable<Users>()
                .Where(a => a.Status == 1 && (a.WorkNumber.Contains(workNumber) || a.UserLoginId.Contains(workNumber)))
                .OrderBy(a => a.CreateDate, OrderByType.Desc)
                .FirstAsync();
        }

        /// <summary>
        /// 更新用户操作版本记录
        /// </summary>
        /// <param name="OptionType"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        private async Task UpdateVersion(string optionType, SaveCustomerProfileConfigInput? input, Guid? id)
        {

            try
            {
                var editor = _dbPlatform.Queryable<Users>().Where(x => x.WorkNumber.Equals(CurrentUser.UserName)).First().UserName;
                var now = DateTime.Now;
                var  editRecords = new List<CustomerProfileEditRecord>();
                if (optionType == "修改")
                {
                    var oldHeader = await _dbBusiness.Queryable<CustomerProfileConfigHeader>().Where(x => x.Id == input.Id).FirstAsync();
                    var oldDetails = await _dbBusiness.Queryable<CustomerProfileConfigDetail>().Where(x => x.ParentId == input.Id).ToListAsync();

                    if (oldHeader != null)
                    {
                        var oldVersion = await _dbBusiness.Queryable<CustomerProfileEditRecord>().Where(x => x.ParentId == input.Id).MaxAsync(x => x.Version);
                        var newVersion = oldVersion + 1;
                        #region
                        int i = 0;
                        if (input.Business != oldHeader.Business)
                        {
                            var editRecord = new CustomerProfileEditRecord()
                            {
                                Id = Guid.NewGuid(),
                                ParentId = input.Id,
                                SortNo = i++,
                                Version = newVersion,
                                FieldCode = "Business",
                                FieldName = "事业部",
                                OldValue = oldHeader.Business,
                                NewValue = input.Business,
                                Editor = editor,
                                OptionType = optionType,
                                CreateTime = now
                            };
                            editRecords.Add(editRecord);
                        }
                        if (input.Industry != oldHeader.Industry)
                        {
                            var editRecord = new CustomerProfileEditRecord()
                            {
                                Id = Guid.NewGuid(),
                                ParentId = input.Id,
                                SortNo = i++,
                                Version = newVersion,
                                FieldCode = "Industry",
                                FieldName = "行业",
                                OldValue = oldHeader.Industry,
                                NewValue = input.Industry,
                                Editor = editor,
                                OptionType = optionType,
                                CreateTime = now
                            };
                            editRecords.Add(editRecord);
                        }
                        if (input.Area != oldHeader.Area)
                        {
                            var editRecord = new CustomerProfileEditRecord()
                            {
                                Id = Guid.NewGuid(),
                                ParentId = input.Id,
                                SortNo = i++,
                                Version = newVersion,
                                FieldCode = "Area",
                                FieldName = "区域",
                                OldValue = oldHeader.Area,
                                NewValue = input.Area,
                                Editor = editor,
                                OptionType = optionType,
                                CreateTime = now
                            };
                            editRecords.Add(editRecord);
                        }
                        if (input.CustomerType != oldHeader.CustomerType)
                        {
                            var editRecord = new CustomerProfileEditRecord()
                            {
                                Id = Guid.NewGuid(),
                                ParentId = input.Id,
                                SortNo = i++,
                                Version = newVersion,
                                FieldCode = "CustomerType",
                                FieldName = "客户类型",
                                OldValue = oldHeader.CustomerType,
                                NewValue = input.CustomerType,
                                Editor = editor,
                                OptionType = optionType,
                                CreateTime = now
                            };
                            editRecords.Add(editRecord);
                        }
                        if (input.CustomerCode != oldHeader.CustomerCode)
                        {
                            var editRecord = new CustomerProfileEditRecord()
                            {
                                Id = Guid.NewGuid(),
                                ParentId = input.Id,
                                SortNo = i++,
                                Version = newVersion,
                                FieldCode = "CustomerCode",
                                FieldName = "送达方代码",
                                OldValue = oldHeader.CustomerCode,
                                NewValue = input.CustomerCode,
                                Editor = editor,
                                OptionType = optionType,
                                CreateTime = now
                            };
                            editRecords.Add(editRecord);
                        }
                        if (input.CustomerName != oldHeader.CustomerName)
                        {
                            var editRecord = new CustomerProfileEditRecord()
                            {
                                Id = Guid.NewGuid(),
                                ParentId = input.Id,
                                Version = newVersion,
                                SortNo = i++,
                                FieldCode = "CustomerName",
                                FieldName = "送达方名称",
                                OldValue = oldHeader.CustomerName,
                                NewValue = input.CustomerName,
                                Editor = editor,
                                OptionType = optionType,
                                CreateTime = now
                            };
                            editRecords.Add(editRecord);
                        }
                        if (input.SDFCode2 != oldHeader.SDFCode2)
                        {
                            var editRecord = new CustomerProfileEditRecord()
                            {
                                Id = Guid.NewGuid(),
                                ParentId = input.Id,
                                SortNo = i++,
                                Version = newVersion,
                                FieldCode = "SDFCode2",
                                FieldName = "售达方代码",
                                OldValue = oldHeader.SDFCode2,
                                NewValue = input.SDFCode2,
                                Editor = editor,
                                OptionType = optionType,
                                CreateTime = now
                            };
                            editRecords.Add(editRecord);
                        }
                        if (input.SDFName2 != oldHeader.SDFName2)
                        {
                            var editRecord = new CustomerProfileEditRecord()
                            {
                                Id = Guid.NewGuid(),
                                ParentId = input.Id,
                                Version = newVersion,
                                SortNo = i++,
                                FieldCode = "SDFName2",
                                FieldName = "售达方名称",
                                OldValue = oldHeader.SDFName2,
                                NewValue = input.SDFName2,
                                Editor = editor,
                                OptionType = optionType,
                                CreateTime = now
                            };
                            editRecords.Add(editRecord);
                        }
                        if (input.ProductionLine != oldHeader.ProductionLine)
                        {
                            var editRecord = new CustomerProfileEditRecord()
                            {
                                Id = Guid.NewGuid(),
                                ParentId = input.Id,
                                SortNo = i++,
                                Version = newVersion,
                                FieldCode = "ProductionLine",
                                FieldName = "产线名称",
                                OldValue = oldHeader.ProductionLine,
                                NewValue = input.ProductionLine,
                                Editor = editor,
                                OptionType = optionType,
                                CreateTime = now
                            };
                            editRecords.Add(editRecord);
                        }
                        if (input.ProductName != oldHeader.ProductName)
                        {
                            var editRecord = new CustomerProfileEditRecord()
                            {
                                Id = Guid.NewGuid(),
                                ParentId = input.Id,
                                SortNo = i++,
                                Version = newVersion,
                                FieldCode = "ProductName",
                                FieldName = "产品名称",
                                OldValue = oldHeader.ProductName,
                                NewValue = input.ProductName,
                                Editor = editor,
                                OptionType = optionType,
                                CreateTime = now
                            };
                            editRecords.Add(editRecord);
                        }
                        if (input.CustomerAttribution != oldHeader.CustomerAttribution)
                        {
                            var editRecord = new CustomerProfileEditRecord()
                            {
                                Id = Guid.NewGuid(),
                                ParentId = input.Id,
                                SortNo = i++,
                                Version = newVersion,
                                FieldCode = "CustomerAttribution",
                                FieldName = "客户归属",
                                OldValue = oldHeader.CustomerAttribution,
                                NewValue = input.CustomerAttribution,
                                Editor = editor,
                                OptionType = optionType,
                                CreateTime = now
                            };
                            editRecords.Add(editRecord);
                        }
                        if (input.State != oldHeader.State)
                        {
                            var editRecord = new CustomerProfileEditRecord()
                            {
                                Id = Guid.NewGuid(),
                                ParentId = input.Id,
                                SortNo = i++,
                                Version = newVersion,
                                FieldCode = "State",
                                FieldName = "状态",
                                OldValue = oldHeader.State,
                                NewValue = input.State,
                                Editor = editor,
                                OptionType = optionType,
                                CreateTime = now
                            };
                            editRecords.Add(editRecord);
                        }
                        if (input.JYDate != oldHeader.JYDate)
                        {
                            var editRecord = new CustomerProfileEditRecord()
                            {
                                Id = Guid.NewGuid(),
                                ParentId = input.Id,
                                SortNo = i++,
                                Version = newVersion,
                                FieldCode = "JYDate",
                                FieldName = "建浴（混槽）日期",
                                OldValue = oldHeader.JYDate,
                                NewValue = input.JYDate,
                                Editor = editor,
                                OptionType = optionType,
                                CreateTime = now
                            };
                            editRecords.Add(editRecord);
                        }
                        if (input.TCORHC != oldHeader.TCORHC)
                        {
                            var editRecord = new CustomerProfileEditRecord()
                            {
                                Id = Guid.NewGuid(),
                                ParentId = input.Id,
                                SortNo = i++,
                                Version = newVersion,
                                FieldCode = "TCORHC",
                                FieldName = "投槽/混槽",
                                OldValue = oldHeader.TCORHC,
                                NewValue = input.TCORHC,
                                Editor = editor,
                                OptionType = optionType,
                                CreateTime = now
                            };
                            editRecords.Add(editRecord);
                        }
                        if (input.Province != oldHeader.Province)
                        {
                            var editRecord = new CustomerProfileEditRecord()
                            {
                                Id = Guid.NewGuid(),
                                ParentId = input.Id,
                                SortNo = i++,
                                Version = newVersion,
                                FieldCode = "Province",
                                FieldName = "客户省份",
                                OldValue = oldHeader.Province,
                                NewValue = input.Province,
                                Editor = editor,
                                OptionType = optionType,
                                CreateTime = now
                            };
                            editRecords.Add(editRecord);
                        }
                        if (input.City != oldHeader.City)
                        {
                            var editRecord = new CustomerProfileEditRecord()
                            {
                                Id = Guid.NewGuid(),
                                ParentId = input.Id,
                                SortNo = i++,
                                Version = newVersion,
                                FieldCode = "City",
                                FieldName = "客户城市",
                                OldValue = oldHeader.City,
                                NewValue = input.City,
                                Editor = editor,
                                OptionType = optionType,
                                CreateTime = now
                            };
                            editRecords.Add(editRecord);
                        }
                        if (input.TestingFrequency != oldHeader.TestingFrequency)
                        {
                            var editRecord = new CustomerProfileEditRecord()
                            {
                                Id = Guid.NewGuid(),
                                ParentId = input.Id,
                                SortNo = i++,
                                Version = newVersion,
                                FieldCode = "TestingFrequency",
                                FieldName = "标准槽液检测频次/月",
                                OldValue = oldHeader.TestingFrequency,
                                NewValue = input.TestingFrequency,
                                Editor = editor,
                                OptionType = optionType,
                                CreateTime = now
                            };
                            editRecords.Add(editRecord);
                        }
                        if (input.JSDDName != oldHeader.JSDDName)
                        {
                            var editRecord = new CustomerProfileEditRecord()
                            {
                                Id = Guid.NewGuid(),
                                ParentId = input.Id,
                                SortNo = i++,
                                Version = newVersion,
                                FieldCode = "JSDDName",
                                FieldName = "技术担当名称",
                                OldValue = oldHeader.JSDDName,
                                NewValue = input.JSDDName,
                                Editor = editor,
                                OptionType = optionType,
                                CreateTime = now
                            };
                            editRecords.Add(editRecord);
                        }
                        if (input.XSDDName != oldHeader.XSDDName)
                        {
                            var editRecord = new CustomerProfileEditRecord()
                            {
                                Id = Guid.NewGuid(),
                                ParentId = input.Id,
                                SortNo = i++,
                                Version = newVersion,
                                FieldCode = "XSDDName",
                                FieldName = "销售担当名称",
                                OldValue = oldHeader.XSDDName,
                                NewValue = input.XSDDName,
                                Editor = editor,
                                OptionType = optionType,
                                CreateTime = now
                            };
                            editRecords.Add(editRecord);
                        }
                        foreach (var item in input.InnerDetails)
                        {
                            var currentItem = oldDetails.Where(m =>m.SortNo ==item.SortNo && m.Project1 == item.Project1 && m.Project2 == item.Project2 && item.Project3 == item.Project3).FirstOrDefault();
                            var fieldName = string.IsNullOrEmpty(item.Project3) ? item.Project1 + "/" + item.Project2  : item.Project1 + "/" + item.Project2 + "/" + item.Project3 ;
                            if (currentItem != null && item.MinValue!=currentItem.MinValue)
                            {
                               
                                var editRecord = new CustomerProfileEditRecord()
                                {
                                    Id = Guid.NewGuid(),
                                    ParentId = input.Id,
                                    SortNo = i++,
                                    Version = newVersion,
                                    FieldCode = "Project",
                                    FieldName = fieldName + "/最小值",
                                    OldValue = currentItem.MinValue,
                                    NewValue = item.MinValue,
                                    Editor = editor,
                                    OptionType = optionType,
                                    CreateTime = now
                                };
                                editRecords.Add(editRecord);
                            }
                            if (currentItem != null && item.MaxValue != currentItem.MaxValue)
                            {
                                var editRecord = new CustomerProfileEditRecord()
                                {
                                    Id = Guid.NewGuid(),
                                    ParentId = input.Id,
                                    SortNo = i++,
                                    Version = newVersion,
                                    FieldCode = "Project",
                                    FieldName = fieldName +"/最大值",
                                    OldValue = currentItem.MaxValue,
                                    NewValue = item.MaxValue,
                                    Editor = editor,
                                    OptionType = optionType,
                                    CreateTime = now
                                };
                                editRecords.Add(editRecord);
                            }
                            if (currentItem != null && item.StandardValue != currentItem.StandardValue)
                            {
                                var editRecord = new CustomerProfileEditRecord()
                                {
                                    Id = Guid.NewGuid(),
                                    ParentId = input.Id,
                                    SortNo = i++,
                                    Version = newVersion,
                                    FieldCode = "Project",
                                    FieldName = fieldName + "/标准值",
                                    OldValue = currentItem.StandardValue,
                                    NewValue = item.StandardValue,
                                    Editor = editor,
                                    OptionType = optionType,
                                    CreateTime = now
                                };
                                editRecords.Add(editRecord);
                            }
                            if (currentItem != null && item.IsEnable != currentItem.IsEnable)
                            {
                                var editRecord = new CustomerProfileEditRecord()
                                {
                                    Id = Guid.NewGuid(),
                                    ParentId = input.Id,
                                    SortNo = i++,
                                    Version = newVersion,
                                    FieldCode = "Project",
                                    FieldName = fieldName + "/是否启用项",
                                    OldValue = currentItem.IsEnable,
                                    NewValue = item.IsEnable,
                                    Editor = editor,
                                    OptionType = optionType,
                                    CreateTime = now
                                };
                                editRecords.Add(editRecord);
                            }
                        }
                        #endregion
                    }
                }
                else
                {
                    var oldHeader = await _dbBusiness.Queryable<CustomerProfileConfigHeader>().Where(x => x.Id == id).FirstAsync();
                    if (oldHeader != null)
                    {
                        var oldVersion = await _dbBusiness.Queryable<CustomerProfileEditRecord>().Where(x => x.ParentId == id).MaxAsync(x => x.Version);
                        var newVersion = oldVersion + 1;
                        var editRecord = new CustomerProfileEditRecord()
                        {
                            Id = Guid.NewGuid(),
                            ParentId = oldHeader.Id,
                            SortNo = 1,
                            Version = newVersion,
                            FieldCode = "",
                            FieldName = "",
                            OldValue = "",
                            NewValue = "",
                            Editor = editor,
                            OptionType = optionType,
                            CreateTime = now
                        };
                        editRecords.Add(editRecord);
                    }
                }
                if (editRecords.Count > 0)
                {
                    await _dbBusiness.Insertable<CustomerProfileEditRecord>(editRecords).ExecuteCommandAsync();
                }
            }
            catch (Exception e)
            {

                throw e;
            }
        }
    }
}
